const $ = require('gulp-load-plugins')();
const gulp = require('gulp');
const path = require('path')
const del = require('del')
var rename = require("gulp-rename");
const {
	src,
	dest,
	series,
	parallel,
} = require('gulp')

let data = {
	name: 'xjp'
}

const browserSync = require('browser-sync').create();
const cwd = process.cwd();
const dir = __dirname;
let config = {
	servePath: 'dist',
	cssPath: 'src/css/*.scss',
	jsPath: 'src/js/*.js',
	htmlPath: 'src/*.html',
	distPath: 'dist',
	src: 'src',
	watchCompile: [
		'src/css/*.scss',
		'src/js/*.js',
		'src/*.html',
	],
	watchReload: [
		'dist/css/*.css',
		'dist/js/*.js',
		'dist/*.html',
	]
}

function css(filename) {
	//filename初始化是done方法，后续是变化的文件名
	const files = typeof filename === 'string' ? filename : config.cssPath;
	return src(files, {
			base: config.src
		})
		.pipe($.sass())
		.pipe(dest(config.distPath))
}

function js(filename) {
	const files = typeof filename === 'string' ? filename : config.jsPath
	return src(files, {
			base: config.src
		})
		.pipe($.babel({
			presets: [require('@babel/preset-env')]
		}))
		.pipe(dest(config.distPath))
}

function devTtml(filename) {
	const files = typeof filename === 'string' ? filename : config.htmlPath
	return src(files, {
			base: config.src
		})
		.pipe($.swig({
			data: data,
			defaults: {
				cache: false,
			}
		}))
		.pipe(dest(config.distPath))
}

function buildJs() {
	return src('src/**/*.js', {
			base: 'src'
		})
		.pipe($.babel({
			presets: [require('@babel/preset-env')]
		}))
		.pipe($.uglify())
		.pipe(dest('dist'))
}

function buildCss() {
	return src('src/**/*.scss', {
			base: 'src'
		})
		.pipe($.sass())
		.pipe($.autoprefixer({
			cascade: false //  是否美化属性值 
		}))
		.pipe($.cleanCss())
		.pipe(dest('dist'))
}

function buildHtml() {
	return src('src/**/*.html', {
			base: 'src'
		})
		.pipe($.swig({
			data: data,
			defaults: {
				cache: false,
			}
		}))
		.pipe($.useref({
			searchPath: 'dist'
		}))
		.pipe(dest('release'))
}

const serve = () => {
	browserSync.init({
		server: {
			baseDir: config.servePath,
		}
	});
	browserSync.watch(config.watchCompile)
		.on('change', (fileName, file) => {
			if (fileName.indexOf('.scss') > -1) {
				css(fileName)
			}
			if (fileName.indexOf('.html') > -1) {
				fnObj = devTtml;
				devTtml(fileName)
			}
			if (fileName.indexOf('.js') > -1) {
				js(fileName)
			}
		})
	browserSync.watch(config.watchReload)
		.on('change', (fileName, file) => {
			browserSync.reload(fileName)
		})
}

function clean() {
	return del(['dist', 'release'])
}

const build = series(clean, parallel(buildJs, buildCss), buildHtml);
const dev = series(clean, parallel(css, devTtml, js), serve);
module.exports = {
	build,
	dev
}
exports.default = serve;
